/**
 * Program  : FireCheckTask.java
 * Author   : long
 * Create   : 2016年5月14日 下午4:50:53
 *
 * Copyright 2016 by Embedded Internet Solutions Inc.,
 * All rights reserved.
 *
 * This software is the confidential and proprietary information
 * of Embedded Internet Solutions Inc.("Confidential Information").  
 * You shall not disclose such Confidential Information and shall 
 * use it only in accordance with the terms of the license agreement 
 * you entered into with Embedded Internet Solutions Inc.
 *
 */
	
package cn.broadin.app.hotel.task;

import com.alibaba.fastjson.JSON;

import android.content.Intent;
import cn.broadin.app.hotel.MainActivity;
import cn.broadin.app.hotel.service.ListenNewVersionService;
import cn.broadin.app.hotel.util.XHttpProxy;
import cn.broadin.app.hotel.util.XLog;

/**
 * 火警检测task
 * 
 * @author   long
 * @version  1.0.0
 * @date 2016年5月14日下午4:50:53
 */
public class FireCheckTask implements Runnable{
	
	private volatile boolean isShowFireView = false;
	
	private String url;
	private MainActivity mActivity;
	
	public FireCheckTask(String url){
		this.url = url;
	}
	
	
	public FireCheckTask(MainActivity activity, String url){
		this.url = url;
		this.mActivity = activity;
	}
	
	@Override
	public void run() {
		
		while(ListenNewVersionService.isRunning){
			try {
				String responseText = XHttpProxy.sendGetRequest(url);
				checkFireStatus(responseText);
				
				Thread.sleep(1000);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		isShowFireView = false;
	}
	
	private void checkFireStatus(String responseText){
		if(responseText == null || "".equals(responseText)){
			return;
		}
		try{
			//{'result':'00000', 'fireFlag':false}
			com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(responseText);
			boolean fireFlag = jsonObject.getBooleanValue("fireFlag");
			if(fireFlag && !isShowFireView){
				// 打开紧急activity
				sendFireBroadcast(MainActivity.FIRE_HAPPEN_ACTION);
//				Intent dialogIntent = new Intent(ListenNewVersionService.mService.getApplicationContext(), FireActivity.class);   
//				dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);   
//				ListenNewVersionService.mService.startActivity(dialogIntent);  
				isShowFireView = true;
			}
			if(!fireFlag && isShowFireView){
				// 警报解除
				sendFireBroadcast(MainActivity.FIRE_OVER_ACTION);
				isShowFireView = false;
			}
		} catch(Exception e){
			e.printStackTrace();
		}
	}
	
	private void sendFireBroadcast(String action) {
		Intent intent = new Intent();
		intent.setAction(action);
		// 发送广播，通知UI层网络改变了
		XLog.i("send broadcase: " + action);
		if(mActivity != null){
			mActivity.getBaseContext().sendBroadcast(intent);	
		} else {
			ListenNewVersionService.mService.sendBroadcast(intent);
		}
	}
}
